import React, { useRef, useState } from 'react';
import { Tabs } from 'antd';
import { formatJSON, formatXML, isJSON } from '@/utils/utils';
import MemoAceEditor from './MemoAceEditor';

const { TabPane } = Tabs;

function isXML(str) {
  if (typeof str === 'string') {
    if (str.trim().startsWith('<')) {
      return true;
    }
  }
  return false;
}

function JsonAndXmlEditor({
  forwardRef,
  activeKey = 'json',
  value,
  style,
  height = 388,
  hideFormat = false,
  readOnly = false,
  title,
}) {
  const editorRef = useRef({ tabKey: 'json' });

  if (forwardRef) {
    forwardRef.current = editorRef.current;
  }

  if (isXML(value)) {
    activeKey = 'xml';
  }

  const type = `${activeKey}`.toLowerCase();
  editorRef.current.tabKey = type;
  editorRef.current.getValue = () => {
    const { jsonEditor, xmlEditor } = editorRef.current;
    if (jsonEditor) {
      return jsonEditor.getValue();
    }
    if (xmlEditor) {
      return xmlEditor.getValue();
    }
    throw new Error('Unknown editor type');
  };

  value = value || undefined;

  const JsonBox = () => {
    const text = formatJSON(value);
    return (
      <>
        {hideFormat ? null : <div className="bold margin-bottom">{title || 'JSON代码'}</div>}
        <MemoAceEditor
          data={text}
          mode={isJSON(text) ? 'json' : 'text'}
          getInstance={instance => {
            editorRef.current.jsonEditor = instance;
          }}
          readOnly={readOnly}
          style={{ ...style, height }}
        />
      </>
    );
  };

  const XmlBox = () => {
    const text = formatXML(value);
    return (
      <>
        {hideFormat ? null : <div className="bold margin-bottom">{title || 'XML代码'}</div>}
        <MemoAceEditor
          data={text}
          mode={isXML(text) ? 'xml' : 'text'}
          getInstance={instance => {
            editorRef.current.xmlEditor = instance;
          }}
          readOnly={readOnly}
          style={{ ...style, height }}
        />
      </>
    );
  };

  const [tabKey, setTabKey] = useState('json');

  if (type === 'json') {
    return JsonBox();
  }

  if (type === 'xml') {
    return XmlBox();
  }

  return (
    <Tabs
      activeKey={tabKey}
      onChange={key => {
        editorRef.current.tabKey = key;
        setTabKey(key);
      }}
    >
      <TabPane tab="JSON" key="json">
        {JsonBox()}
      </TabPane>
      <TabPane tab="XML" key="xml">
        {XmlBox()}
      </TabPane>
    </Tabs>
  );
}

export default React.forwardRef((props, ref) => {
  return <JsonAndXmlEditor {...props} forwardRef={ref} />;
});
